<?php
include_once("inc.admin.php");

$this_title="$vars[admin_title] - Database";

$result_per_page=50;

//table input
$table=$_GET["tbl"];
$page=$_GET["nav"];

//view
if($_GET["aj"] && $_GET["tbl"] && $_GET["view"]){
 if(!$pv["db"][$table]["view"]){
  print "You do not have the privilege to view this table.";
  exit;
 }
 //search
 if($_GET["search"]){
  $i=$ai=$oi=0;
  foreach($_GET as $post => $value){
   if(substr($post, 0, 3)=="_fs" && strlen($value)){
    $field=substr($post, 3);
    $r_search[$i]["field"]=$field;
    $r_search[$i]["value"]=StripSlashes($value);
    $r_search[$i]["option"]=$_GET["_fa$field"];
    if($_GET["_fa$field"]=="a"){//and
     $r_and_search[$ai]["field"]=$field;
     $r_and_search[$ai]["value"]=$value;
     $ai++;
    }else{                               
     $r_or_search[$oi]["field"]=$field;
     $r_or_search[$oi]["value"]=$value;
     $oi++;
    }
    $i++;
   }
  }
  if(count($r_and_search) || count($r_or_search)){
   $search_separator=",";
   for($i=0;$i<count($r_and_search);$i++){
    $search_term="";
    $r_search_term=explode($search_separator, $r_and_search[$i]["value"]);
    for($j=0;$j<count($r_search_term);$j++){
     $search_term.=($search_term? "," : "")."'$r_search_term[$j]'";
    }
    $and_search.=($and_search? " and " : "").$r_and_search[$i]["field"]." in ($search_term)";
   }
   if($and_search){
    $combine_search="($and_search)";
   }

   for($i=0;$i<count($r_or_search);$i++){   
    $search_term="";
    $r_search_term=explode($search_separator, $r_or_search[$i]["value"]);
    for($j=0;$j<count($r_search_term);$j++){
     $search_term.=($search_term? "," : "")."'$r_search_term[$j]'";
    }
    $or_search.=($or_search? " or " : "").$r_or_search[$i]["field"]." in ($search_term)";
   }
   if($or_search){
    if($combine_search){
     $combine_search.=" or ($or_search)";
    }else{
     $combine_search="($or_search)";
    }
   }

   if($combine_search){
    $search_str="where $combine_search";
   }
  }else{
   $fm_search=0;
  }
 }// end search
 $result=get_table($table, $result_per_page, $page, $search_str);
 $page=$result["page"];
 $total_page=$result["total_page"];
 $record_count=$result["record_count"];
 $r_table_field=$result["table_field"];
 $r_table_index=$result["table_index"];
 $r_table_content=$result["table_content"];
 $get=$_GET;
 unset($get["aj"]);
 unset($get["view"]);
 $page_d=format_page_admin_aj($page, $total_page, $this_file);

 //table field index
 foreach($r_table_field as $index=>$field){
  $r_table_field_index[$field]=$index;
 }

 //total record
 $table_name=($tr_table[$table]["name"]? $tr_table[$table]["name"] : $table);
 $table_total_record="$table_name table, $record_count record".($record_count>1? "s" : "")." found";

 //table content
 for($i=0;$i<count($r_table_content);$i++){
  $table_col="";
  for($j=0;$j<count($r_table_content[$i]);$j++){
   $field=$r_table_content[$i][$j]["field"];
   $value=$r_table_content[$i][$j]["value"];
   if($field=="id"){
    $id=$value;
   }
   $table_col.="
   <td class='tblf_$r_table_field_index[$field]'>".nhtmlentities($value)."</td>";
  }
  if($pv["db"][$table]["edit"]){
   $edit_col="<td><a href='' class='edit_table_record'><img src='".M_URL."/images/icons/edit.png' border=0></a></td>";
  }
  if($pv["db"][$table]["delete"]){
   $delete_col="<td><a href='' class='delete_table_record'><img src='".M_URL."/images/icons/delete.png' border=0></a></td>";
  }
  $table_row.="
  <tr class='ams_body' id='tbl_row_$i'>".$edit_col.$delete_col.$table_col."</tr>";
 }

 //table header
 for($i=0;$i<count($r_table_field);$i++){
  $field=$r_table_field[$i]; 
  $table_header.="
  <td>$field</td>";
 }
 if($pv["db"][$table]["edit"]){
  $table_header="<td></td>$table_header";
 }
 if($pv["db"][$table]["delete"]){
  $table_header="<td></td>$table_header";
 }
 $table_header="<tr class='ams_header'>$table_header</tr>";
 $table_list="
 $table_total_record
 $page_d
 <table class='ams_table'>
 $table_header
 $table_row
 </table>
 $page_d";

 print $table_list;
 exit;
}

//add
if($_GET["aj"] && $_GET["add"] && count($_POST)){
 if(!$pv["db"][$table]["add"]){
  $errmsg.="You do not have the privilege to add record to this table.";
 }else{
   foreach($_POST as $post=>$value){
   $post_a[$post]=get_magic_quotes_gpc()? $value : AddSlashes($value);
   $post_s[$post]=get_magic_quotes_gpc()? StripSlashes($value) : $value;
  }
  $r_pri=array();
  if($post_s["table_primary"]){
   $r_pri=explode(",", $post_s["table_primary"]);
  }

  foreach($post_a as $field=>$value){
   if(substr($field, 0, strlen("_field_"))=="_field_"){
    $real_field=substr($field, strlen("_field_"));
    if(!in_array($real_field, $r_pri) || strlen($value)){
     $sql_field.=$real_field.", ";
     $sql_value.="'$value', ";
    }
   }
  }
  $sql_field=rtrim($sql_field, ", ");
  $sql_value=rtrim($sql_value, ", ");
  $sql="insert into $table ($sql_field) values ($sql_value)";
  if(!mysql_query($sql)){
   $errmsg.="Error adding record to the table '$table'. ".mysql_error();
  }else{
   $msg="Record is added successfully.";
  }
 }
 $status=$errmsg? 2 : 1;
 $xml="<?xml version=\"1.0\" encoding='$vars[charset]'?>
<response>
<status>$status</status>
<msg>$msg$errmsg</msg>
</response>";
 header("Content-type: text/xml");
 header("Cache-Control: no-cache");
 print $xml;
 exit;
}

//edit
if($_GET["aj"] && $_GET["edit"] && count($_POST)){
 if(!$pv["db"][$table]["edit"]){
  $errmsg.="You do not have the privilege to update record in this table.";
 }else{
   foreach($_POST as $post=>$value){
   $post_a[$post]=get_magic_quotes_gpc()? $value : AddSlashes($value);
   $post_s[$post]=get_magic_quotes_gpc()? StripSlashes($value) : $value;
  }
  foreach($post_a as $field=>$value){
   if(substr($field, 0, strlen("_field_"))=="_field_"){
    $sql_field_value.=substr($field, strlen("_field_"))."='$value', ";
   }elseif(substr($field, 0, strlen("_orig_field_"))=="_orig_field_"){
    $r_orig_field[substr($field, strlen("_orig_field_"))]=$value;
   }
  }
  $sql_field_value=rtrim($sql_field_value, ", ");
  if($post_s["table_primary"]){
   $r_pri=explode(",", $post_s["table_primary"]);
   foreach($r_pri as $pri){
    $where.=($where? " and " : "")."$pri='".$r_orig_field[$pri]."'";
   }
  }elseif($post_s["table_unique"]){
   $r_uni=explode(",", $post_s["table_unique"]);
   foreach($r_uni as $uni){
    $where.=($where? " and " : "")."$uni='".$r_orig_field[$uni]."'";
   }
  }else{
   foreach($r_orig_field as $field=>$value){
    $where.=($where? " and " : "")."$field='$value'";
   }
  }
  $sql="update $table set $sql_field_value where $where limit 1";
  if(!mysql_query($sql)){
   $errmsg.="Error updating the table '$table'. ".mysql_error();
  }else{
   $msg="Update is successful.";
  }
 }
 $status=$errmsg? 2 : 1;
 $xml="<?xml version=\"1.0\" encoding='$vars[charset]'?>
<response>
<status>$status</status>
<msg>$msg$errmsg</msg>
</response>";
 header("Content-type: text/xml");
 header("Cache-Control: no-cache");
 print $xml;
 exit;
}

//delete
if($_GET["aj"] && $_GET["delete"] && count($_POST)){
 if(!$pv["db"][$table]["delete"]){
  $errmsg.="You do not have the privilege to delete record from this table.";
 }else{
  foreach($_POST as $post=>$value){
   $post_a[$post]=get_magic_quotes_gpc()? $value : AddSlashes($value);
   $post_s[$post]=get_magic_quotes_gpc()? StripSlashes($value) : $value;
  }
  foreach($post_a as $field=>$value){
   if(substr($field, 0, strlen("_orig_field_"))=="_orig_field_"){
    $where.=($where? " and " : "").substr($field, strlen("_orig_field_"))."='$value'";
   }
  }
  if($where){
   $sql="delete from $table where $where limit 1";
   if(!mysql_query($sql)){
    $errmsg.="Error deleting the record from the table. ".mysql_error();
   }
  }else{
   $errmsg.="Error deleting the record from the table.";
  }
 }
 $status=$errmsg? 2 : 1;
 $xml="<?xml version=\"1.0\" encoding='$vars[charset]'?>
<response>
<status>$status</status>
<msg>$msg$errmsg</msg>
</response>";
 header("Content-type: text/xml");
 header("Cache-Control: no-cache");
 print $xml;
 exit;
}

if($table && $pv["db"][$table]["view"]){
 $r=mysql_query("show columns from $table");
 for($i=0;$i<mysql_num_rows($r);$i++){
  $r_table_field[]=mysql_result($r, $i);
 }
 $r=mysql_query("show index from $table");
 for($i=0;$i<mysql_num_rows($r);$i++){
  $r_table_index[]=mysql_fetch_array($r);
 }

 //search
 for($i=0;$i<count($r_table_field);$i++){
  $search_str=$and_checked=$or_checked="";
  for($j=0;$j<count($r_search);$j++){
   if($r_search[$j]["field"]==$r_table_field[$i]){
    $search_str=$r_search[$j]["value"];
    if($r_search[$j]["option"]=="a"){//and
     $and_checked="checked";
    }else{
     $or_checked="checked";
    }
    $j=count($r_search);
   }
  }
  if(!$and_checked && !$or_checked){
   $and_checked="checked";
  }
  $option_row.="
  <tr><td><input type=radio name=_fa$r_table_field[$i] value=a $and_checked id=$r_table_field[$i]></td><td><input type=radio name=_fa$r_table_field[$i] value=o $or_checked id=$r_table_field[$i]></td><td><label for=$r_table_field[$i]>$r_table_field[$i]</label></td><td><input type=text name=_fs$r_table_field[$i] value=\"$search_str\" class=inputbox></td></tr>";
 }
 $search="
 <div id='search_div'>
 <p class=bold>Search: <a href='' class='search_a'>Show</a></p>
 <form name='search_form' id='search_form' method='post' action=''>
 <input type='hidden' name='nav' value='$page' />
 <input type='hidden' name='search' value='1' />
 <table border='0' id='search_block' style='display:none;'>
  <tr>
   <td>And</td>
   <td>Or</td>
   <td>Field</td>
   <td>Search String</td>
  </tr>
  $option_row
  <tr>
   <td colspan='4'><input type='submit' value='Search' id='search_btn' /> <input type='button' name='clear_search' value='Clear search & refresh' /></td>
  </tr>
 </table>
 </form>
 </div>";

 //column span
 $colspan=0;
 if($pv["db"][$table]["edit"]){
  $colspan++;
 }
 if($pv["db"][$table]["delete"]){
  $colspan++;
 }

 //add record privilege
 if($pv["db"][$table]["add"]){
  $table_add_record="<a href='' class='add_table_record'>Add Record</a>";
 }

 //javascript
 foreach($r_table_field as $index=>$field){
  $table_field_arr_jv.="tbl_field['".AddSlashes($field)."']=Array();\n";
  $table_field_jv.="tbl_field['".AddSlashes($field)."']['index']='$index';\n";
  $table_index_field_jv.="tbl_index_field['$index']='".AddSlashes($field)."';\n";
 }
 $r=mysql_query("show fields from $table");
 while($row=mysql_fetch_array($r)){
  $table_field_jv.="tbl_field['".AddSlashes($row["Field"])."']['type']='".(strstr($row["Type"], "text")? "text" : "normal")."';\n";
 }
 for($i=0;$i<count($r_table_index);$i++){
  if($r_table_index[$i]["Key_name"]=="PRIMARY"){
   $table_primary_jv.=$r_table_index[$i]["Column_name"].",";
  }elseif($r_table_index[$i]["Non_unique"]=="0"){
   $table_unique_jv.=$r_table_index[$i]["Column_name"].",";
  }
 }
 $table_primary_jv=rtrim($table_primary_jv, ",");
 $table_unique_jv=rtrim($table_unique_jv, ",");

 $jvscript=
 "<script type='text/javascript' src='".JS_URL."/get_file_gzip.php?file=".urlencode("jquery.js,jquery.livequery.js")."'></script>
 <script type='text/javascript' src='".JS_URL."/get_file_gzip.php?file=".urlencode("fn/fn_htmlentities.js")."'></script>
 <script type='text/javascript'>
 var tbl_field=new Array();
 $table_field_arr_jv
 $table_field_jv
 var tbl_index_field=new Array();
 $table_index_field_jv
 var table_primary='$table_primary_jv';
 var table_unique='$table_unique_jv';
 var colspan=$colspan;
 var field_colspan=".count($r_table_field).";

 jQuery(document).ready(function(\$){
  refresh_table();

  "./*Add table record*/
  "\$('a.add_table_record').click(function(){ 
   if(\$('div#add_record_div').html()==null){
    var add_field='';
    for(each_field in tbl_field){
     if(tbl_field[each_field]['type']=='text'){
      ed_field='<textarea name=\"_field_'+each_field+'\" rows=\"5\" class=\"width100\"></textarea>';
     }else{
      ed_field='<input type=\"text\" name=\"_field_'+each_field+'\" class=\"width100\" />';
     }
     add_field+='<tr class=\"ams_body\"><td>'+each_field+': </td><td>'+ed_field+'</td></tr>';
    }
    var add_record='<div id=\"add_record_div\"><form name=\"add_table\" method=\"post\" action=\"$this_file?aj=1&tbl=$table&add=1\" target=_blank><input type=\"hidden\" name=\"do_add\" value=\"1\" /><input type=\"hidden\" name=\"table_primary\" value=\"'+table_primary+'\" /><input type=\"hidden\" name=\"table_unique\" value=\"'+table_unique+'\" /><table class=\"ams_table\"><tr class=\"ams_header\"><td>Field</td><td>Value</td></tr>'+add_field+'<tr><td colspan=\"2\"><input type=\"button\" name=\"add_submit\" value=\"Add\" /> <input type=\"button\" name=\"add_cancel\" value=\"Cancel\" /><div id=\"msgbox\"></div></td></tr></table></form></div>';
    \$(this).after(add_record);
   }
   return false;
  });

  \$('input[@name=add_cancel]').livequery('click', function(){
   \$('div#add_record_div').remove();
  });

  \$('input[@name=add_submit]').livequery('click', function(){
   \$('form[@name=add_table]').submit();
   return false;
  });

  \$('form[@name=add_table]').livequery('submit', function(){
   \$('input[@name=add_submit]').attr('disabled','disabled');
   \$('input[@name=add_cancel]').attr('disabled','disabled');
   \$.ajax({
    type: 'post',
    url: '$this_file?aj=1&tbl=$table&add=1',
    data: \$('form[@name=add_table]').serialize(),
    dataType: 'xml',
    error: function(){
     \$('div#msgbox').html('Opps.. some error occur');
    },
    success: function(data){
     var mesg='';
     if(\$('loggedout', data).text()=='loggedout'){
      mesg='You have been logged out.';
     }else{
      \$(data).find('msg').each(function(){
       mesg+=\$(this).text()+'<br />';
      });
     }
     var status=\$(data).find('status').text();
     \$('div#msgbox').html(mesg).addClass(status==1? 'msg_msg' : 'msg_err');
     if(status=='1'){"./*success*/"
      refresh_table();
     }
    },
    complete: function(){
     \$('input[@name=add_submit]').attr('disabled','');
     \$('input[@name=add_cancel]').attr('disabled','');
    }
   });
   return false;
  });

  "./*Edit table record*/
  "var edit_row_id='';
  \$('a.edit_table_record').livequery('click', function(){
   if(\$('tr#tbl_edit_row').html()==null){
    var parent=\$(this).parent().parent();
    edit_row_id=parent.attr('id');
    var edit_field='';
    var orig_field_value='';
    for(each_field in tbl_field){
     field_value=parent.children('td.tblf_'+tbl_field[each_field]['index']).text();
     if(tbl_field[each_field]['type']=='text'){
      ed_field='<textarea name=\"_field_'+each_field+'\" rows=\"5\" class=\"width100\">'+htmlentities(field_value)+'</textarea>';
     }else{
      ed_field='<input type=\"text\" name=\"_field_'+each_field+'\" class=\"width100\" value=\"'+htmlentities(field_value)+'\" />';
     }
     orig_field_value+='<input type=\"hidden\" name=\"_orig_field_'+each_field+'\" value=\"'+htmlentities(field_value)+'\" />';
     edit_field+='<tr class=\"ams_body\"><td>'+each_field+': </td><td>'+ed_field+'</td></tr>';
    }
    var edit_row='".
    "<tr id=\"tbl_edit_row\"><td colspan=\"'+colspan+'\"></td><td colspan=\"'+field_colspan+'\">".
     "<form name=\"edit_table\" method=\"post\" action=\"$this_file?aj=1&tbl=$table&edit=1\" target=\"_blank\"><input type=\"hidden\" name=\"do_edit\" value=\"1\" /><input type=\"hidden\" name=\"table_primary\" value=\"'+table_primary+'\" /><input type=\"hidden\" name=\"table_unique\" value=\"'+table_unique+'\" />'+orig_field_value+'<table class=\"ams_table\"><tr class=\"ams_header\"><td>Field</td><td>Value</td></tr>'+edit_field+'<tr><td colspan=\"2\"><input type=\"button\" name=\"update_submit\" value=\"Update\" /> <input type=\"button\" name=\"update_cancel\" value=\"Cancel\" /><div id=\"msgbox\"></div></td></tr></table></form>".
    "</td></tr>';
    parent.after(edit_row);
   }
   return false;
  });

  \$('input[@name=update_submit]').livequery('click', function(){
   \$('form[@name=edit_table]').submit();
   return false;
  });

  \$('form[@name=edit_table]').livequery('submit', function(){
  \$('input[@name=update_submit]').attr('disabled','disabled');
   \$('input[@name=update_cancel]').attr('disabled','disabled');
   var new_field_value=new Array();
   \$('input[@name^=_field_]').each(function(){
    var field_name=\$(this).attr('name').substr(7);//\$('div#msgbox').append(\$(this).attr('name')+'<br>');
    new_field_value[tbl_field[field_name]['index']]=\$(this).val();
   });
   \$('textarea[@name^=_field_]').each(function(){
    var field_name=\$(this).attr('name').substr(7);
    new_field_value[tbl_field[field_name]['index']]=\$(this).val();
   });
   \$.ajax({
    type: 'post',
    url: '$this_file?aj=1&tbl=$table&edit=1',
    data: \$('form[@name=edit_table]').serialize(),
    dataType: 'xml',
    error: function(){
     \$('div#msgbox').html('Opps.. some error occur');
    },
    success: function(data){
     var mesg='';
     if(\$('loggedout', data).text()=='loggedout'){
      mesg='You have been logged out.';
     }else{
      \$(data).find('msg').each(function(){
       mesg+=\$(this).text()+'<br />';
      });
     }
     var status=\$(data).find('status').text();
     \$('div#msgbox').html(mesg).addClass(status==1? 'msg_msg' : 'msg_err');
     if(status=='1'){"./*success*/"
      for(each_index in tbl_index_field){
       \$('tr#'+edit_row_id).children('td.tblf_'+each_index).html(htmlentities(new_field_value[each_index]));
      }
     }
    },
    complete: function(){
     \$('input[@name=update_submit]').attr('disabled','');
     \$('input[@name=update_cancel]').attr('disabled','');
    }
   });
   return false;
  });

  \$('input[@name=update_cancel]').livequery('click', function(){
   \$('tr#tbl_edit_row').remove();
  });

  "./*Delete table record*/
  "\$('a.delete_table_record').livequery('click', function(){
   var parent=\$(this).parent().parent();
   var delete_row_id=parent.attr('id');
   var this_record='', orig_field_value='', orig_field_value2='';
   if(table_primary!=''){
    var primary=table_primary.split(',');
    for(i=0;i<primary.length;i++){
     field_value=parent.children('td.tblf_'+tbl_field[primary[i]]['index']).text();
     this_record+='\\n'+primary[i]+': '+field_value;
     orig_field_value+='<input type=\"hidden\" name=\"_orig_field_'+primary[i]+'\" value=\"'+field_value+'\" />';
    }
   }else if(table_unique!=''){
    var unique=table_unique.split(',');
    for(i=0;i<unique.length;i++){
     field_value=parent.children('td.tblf_'+tbl_field[unique[i]]['index']).text();
     orig_field_value+='<input type=\"hidden\" name=\"_orig_field_'+unique[i]+'\" value=\"'+field_value+'\" />';
    }
   }
   if(this_record==''){
    for(each_field in tbl_field){
     field_value=parent.children('td.tblf_'+tbl_field[each_field]['index']).text();
     this_record+='\\n'+each_field+': '+field_value;
     orig_field_value2+='<input type=\"hidden\" name=\"_orig_field_'+each_field+'\" value=\"'+field_value+'\" />';
    }
   }
   orig_field_value=(!orig_field_value? orig_field_value2 : orig_field_value);
   if(confirm('Do you really want to delete the record below with:\\n'+this_record)){
    var delete_form='<form name=\"delete_record\" method=\"post\" target=\"_blank\"><input type=\"hidden\" name=\"do_delete\" value=\"1\" />'+orig_field_value+'</form>';
    \$('div#table_content').append(delete_form);
    \$('form[@name=delete_record]').attr('action', '$this_file?aj=1&tbl=$table&delete=1').submit(function(){
     \$.ajax({
      type: 'post',
      url: '$this_file?aj=1&tbl=$table&delete=1',
      data: \$('form[@name=delete_record]').serialize(),
      dataType: 'xml',
      error: function(){
       alert('Opps.. some error occur');
      },
      success: function(data){
       var mesg='';
       if(\$('loggedout', data).text()=='loggedout'){
        mesg='You have been logged out.';
       }else{
        \$(data).find('msg').each(function(){
         mesg+=\$(this).text()+'\\n';
        });
       }
       var status=\$(data).find('status').text();
       if(status=='1'){"./*success*/"
        \$('tr#'+delete_row_id).after('<tr id=\"delete_row_msg\" class=\"ams_body\"><td colspan=\"'+(colspan+field_colspan)+'\">Record deleted successfully</td><tr>').remove();
        setTimeout('refresh_table()', 1000);
       }else{
        alert(mesg);
       }
      },
      complete: function(){
       \$('form[@name=delete_record]').remove();
      }
     });
     return false;
    }).submit();
   }
   return false;
  });

  "./*search hide/show*/
  "\$('a.search_a').livequery('click', function(){
   if(\$(this).text()=='Show'){
    \$('table#search_block').css('display','block');
    \$(this).text('Hide');
   }else{
    \$('table#search_block').css('display','none');
    \$(this).text('Show');
   }
   return false;
  });

  "./*Search record*/
  "\$('form#search_form').submit(function(){
   var search_str=\$('form#search_form').serialize();
   var post_url=parent.location.href.replace(/#.*/, '')+'#'+search_str;  \$('div#test1').html(post_url);
   parent.location.href=post_url;
   refresh_table();
   return false;
  });

  "./*Clear search & refresh*/
  "\$('input[@name=clear_search]').click(function(){
   \$('input[@name^=_fa]').each(function(){
    \$(this).val('a');
   });
   \$('input[@name^=_fs]').each(function(){
    \$(this).val('');
   });
   var loc=parent.location.href.replace(/#.*/, '')+'#';
   parent.location.href=loc;
   refresh_table();
   return false;
  });

  "./*navigational*/
  "\$('span.nav_page > a.nav').livequery('click', function(){
   var post_url=parent.location.href;
   var nav_rex=new RegExp(/nav=\d*/);
   var nav=nav_rex.exec(\$(this).attr('href'));
   if(post_url.match(/nav=\d*/)){
    post_url=post_url.replace(/nav=\d*/, nav);
   }else if(post_url.match(/#\$/)){
    post_url+=nav;
   }else if(post_url.match(/#.+/)){
    post_url+='&'+nav;                                
   }else{
    post_url+='#'+nav;
   }
   parent.location.href=post_url;
   refresh_table();
   return false;
  });

  "./*goto page navigational*/
	"\$('form[@name=_paging_form]').livequery('submit', function(){
		var post_url=parent.location.href;
		var nav='nav='+\$('input#nav').val();
		if(post_url.match(/nav=\d*/)){
			post_url=post_url.replace(/nav=\d*/, nav);
		}else if(post_url.match(/#\$/)){
			post_url+=nav;
		}else if(post_url.match(/#.+/)){
			post_url+='&'+nav;                                
		}else{
			post_url+='#'+nav;
		}
		parent.location.href=post_url;
		refresh_table();
		return false;
	});
 });

 "./*Refresh table*/
 "function refresh_table(){
  \$('div#table_content').html('Refreshing');
  var qs = window.location.search.substring(1);"./*this will get the querystring, excluding the '?', and will stop when it reaches a '#' (string behind the '#', if found, will be ignored), for eg, for url abc.php?a=1&b=2#c=3, it will extract a=1&b=2*/"
  qs=qs.substr(0, 1)=='&'? qs.substr(1) : qs;
  qs=qs.replace(/tbl=.+/, '');
  var hash_qs=parent.location.href;
  if(hash_qs.match(/#/)){
   hash_qs=parent.location.href.replace(/.+#/, '');"./*this will get the querystring, starting from the '#' (but excluding '#'), if found. for eg, for url abc.php?a=1#b=2, it will extract b=2*/"
  }else{
   hash_qs='';
  }
  hash_qs=hash_qs.substr(0, 1)=='&'? hash_qs.substr(1) : hash_qs;
  var post_url='$this_file?aj=1&tbl=$table&view=1'+(qs!=''? '&'+qs : '')+(hash_qs!=''? '&'+hash_qs : '');

  \$.ajax({
   type: 'post',
   url: post_url,
   dataType: 'html',
   error: function(){
    \$('div#table_content').html('Opps.. some error occur');
   },
   success: function(data){
    var mesg=data;
    if(\$('loggedout', data).text()=='loggedout'){
     mesg='You have been logged out.';
    }
    \$('div#table_content').html(mesg);
   }
  });
 }
 </script>";

 $content="
 <h3>Table List for $table</h3>
 $search
 $table_add_record
 <div id='table_content'></div>";
}else{
 $content="You do not have the privilege to view this table.";
}

print format_admin_page($content, $this_title, $jvscript);

function get_table($in_table, $in_result_per_page, $in_page, $in_search_str){
 $page=(!$in_page || !is_numeric($in_page) || $in_page<1? 1 : $in_page);

 $row_count=mysql_result(mysql_query($s="select count(*) from $in_table $in_search_str"), 0);
 $last_page=ceil($row_count/$in_result_per_page);
 $page=$page>$last_page? $last_page : $page;
 $limit_start=($page-1)*$in_result_per_page;

 $r=mysql_query("show columns from $in_table");
 for($i=0;$i<mysql_num_rows($r);$i++){
  $r_table_field[]=mysql_result($r, $i);
 }
 $r=mysql_query("show index from $in_table");
 for($i=0;$i<mysql_num_rows($r);$i++){
  $r_table_index[]=mysql_fetch_array($r);
  if($r_table_index[$i]["Key_name"]=="PRIMARY"){
   $table_primary_key.=$r_table_index[$i]["Column_name"].",";
  }
 }
 $table_primary_key=rtrim($table_primary_key, ",");

 $sql2="select * from $in_table $in_search_str ".($table_primary_key? "order by $table_primary_key" : "")." limit $limit_start, $in_result_per_page";
 $r2=mysql_query($sql2);
 $i=0;
 if($r2){
  while ($Row = mysql_fetch_array($r2)){
   $j=$k=0;
   foreach($Row as $field => $value){
    if(($k%2)){//skip numerical index value
     $r_detail[$i][$j]["field"] = $field;
     $r_detail[$i][$j]["value"] = $value;
     $j++;
    }
    $k++;
   }
   $i++;
  }
 }

 $r_table["page"]=$page;
 $r_table["total_page"]=$last_page;
 $r_table["record_count"]=$row_count;
 $r_table["table_field"]=$r_table_field;
 $r_table["table_index"]=$r_table_index;
 $r_table["table_content"]=$r_detail;

 return $r_table;
}
?>